//
//  FilterPanelView.m
//  WHTestDome
//
//  Created by Assistant on 9/22/25.
//

#import "FilterPanelView.h"
#import "FilterViewController.h"

@interface FilterPanelView () <FilterViewControllerDelegate>

@property (nonatomic, weak) UIViewController *hostVC;
@property (nonatomic, strong) UIView *dimmingView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) FilterViewController *filterVC;
@property (nonatomic, strong) NSLayoutConstraint *topConstraint;
@property (nonatomic, strong) NSLayoutConstraint *heightConstraint;

@end

@implementation FilterPanelView

- (instancetype)initWithHostViewController:(UIViewController *)hostViewController options:(NSArray<NSString *> * _Nullable)options title:(NSString*)title {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        _hostVC = hostViewController;

        self.translatesAutoresizingMaskIntoConstraints = NO;
        self.backgroundColor = [UIColor clearColor];

        _dimmingView = [[UIView alloc] initWithFrame:CGRectZero];
        _dimmingView.translatesAutoresizingMaskIntoConstraints = NO;
        _dimmingView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        _dimmingView.alpha = 0.0;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
        [_dimmingView addGestureRecognizer:tap];

        _containerView = [[UIView alloc] initWithFrame:CGRectZero];
        _containerView.translatesAutoresizingMaskIntoConstraints = NO;
        _containerView.backgroundColor = [UIColor systemBackgroundColor];
        //_containerView.layer.cornerRadius = 10.0;
        _containerView.layer.masksToBounds = YES;

        _filterVC = [[FilterViewController alloc] init];
        _filterVC.delegate = self;
        if (title.length > 0) { _filterVC.titleName = title;}
        if (options.count > 0) { _filterVC.options = options;}
    }
    return self;
}

- (BOOL)isVisible {
    return self.superview != nil && self.dimmingView.alpha > 0.01;
}

- (CGFloat)calculatedPanelHeightForHost:(UIView *)host {
    [host layoutIfNeeded];
    CGFloat hostHeight = host.bounds.size.height > 0 ? host.bounds.size.height : UIScreen.mainScreen.bounds.size.height;
    CGFloat maxHeight = hostHeight * 0.5; // at most half screen
    // Ask child VC for preferred height within this max
    CGFloat preferred = 0.0;
    if ([self.filterVC respondsToSelector:@selector(preferredContentHeightWithMax:)]) {
        preferred = [self.filterVC preferredContentHeightWithMax:maxHeight];
    }
    if (preferred <= 0.0) { preferred = maxHeight; }
    // Clamp between minHeight and maxHeight
    CGFloat minHeight = 200.0;
    if (preferred < minHeight) preferred = minHeight;
    if (preferred > maxHeight) preferred = maxHeight;
    return preferred;
}

- (CGFloat)safeAreaTopInsetOfHost:(UIView *)host {
    if (@available(iOS 11.0, *)) {
        return host.safeAreaInsets.top;
    }
    return 64.0; // fallback
}

- (void)attachIfNeeded {
    if (!self.superview && self.hostVC) {
        UIView *host = self.hostVC.view;
        [host addSubview:self];
        [NSLayoutConstraint activateConstraints:@[
            [self.topAnchor constraintEqualToAnchor:host.topAnchor],
            [self.leftAnchor constraintEqualToAnchor:host.leftAnchor],
            [self.rightAnchor constraintEqualToAnchor:host.rightAnchor],
            [self.bottomAnchor constraintEqualToAnchor:host.bottomAnchor]
        ]];

        [self addSubview:self.dimmingView];
        [NSLayoutConstraint activateConstraints:@[
            [self.dimmingView.topAnchor constraintEqualToAnchor:self.topAnchor constant: host.safeAreaInsets.top],
            [self.dimmingView.leftAnchor constraintEqualToAnchor:self.leftAnchor],
            [self.dimmingView.rightAnchor constraintEqualToAnchor:self.rightAnchor],
            [self.dimmingView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]
        ]];

        [self addSubview:self.containerView];
        CGFloat panelHeight = [self calculatedPanelHeightForHost:host];
        CGFloat hiddenOffset = - (panelHeight + [self safeAreaTopInsetOfHost:host]);
        self.topConstraint = [self.containerView.topAnchor constraintEqualToAnchor:self.safeAreaLayoutGuide.topAnchor constant:hiddenOffset];
        [NSLayoutConstraint activateConstraints:@[
            self.topConstraint,
            [self.containerView.leftAnchor constraintEqualToAnchor:self.leftAnchor],
            [self.containerView.rightAnchor constraintEqualToAnchor:self.rightAnchor],
            (self.heightConstraint = [self.containerView.heightAnchor constraintEqualToConstant:panelHeight])
        ]];

        // Embed child VC
        [self.hostVC addChildViewController:self.filterVC];
        self.filterVC.view.translatesAutoresizingMaskIntoConstraints = NO;
        [self.containerView addSubview:self.filterVC.view];
        [NSLayoutConstraint activateConstraints:@[
            [self.filterVC.view.topAnchor constraintEqualToAnchor:self.containerView.topAnchor],
            [self.filterVC.view.leftAnchor constraintEqualToAnchor:self.containerView.leftAnchor],
            [self.filterVC.view.rightAnchor constraintEqualToAnchor:self.containerView.rightAnchor],
            [self.filterVC.view.bottomAnchor constraintEqualToAnchor:self.containerView.bottomAnchor]
        ]];
        [self.filterVC didMoveToParentViewController:self.hostVC];
    }
}

- (void)show {
    [self attachIfNeeded];
    // Update height on every show to be robust (e.g., after rotation)
    UIView *host = self.hostVC.view;
    CGFloat panelHeight = [self calculatedPanelHeightForHost:host];
    self.heightConstraint.constant = panelHeight;
    self.topConstraint.constant = - (panelHeight + [self safeAreaTopInsetOfHost:host]);
    [host layoutIfNeeded];
    [UIView animateWithDuration:0.28 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.dimmingView.alpha = 1.0;
        self.topConstraint.constant = 0.0;
        [host layoutIfNeeded];
    } completion:nil];
}

- (void)dismiss {
    if (!self.superview) { return; }
    UIView *host = self.hostVC.view;
    CGFloat panelHeight = self.heightConstraint ? self.heightConstraint.constant : (self.containerView.bounds.size.height > 0 ? self.containerView.bounds.size.height : 400.0);
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            self.dimmingView.alpha = 0.0;
            self.topConstraint.constant = - (panelHeight + [self safeAreaTopInsetOfHost:host]);
            [host layoutIfNeeded];
        } completion:^(BOOL finished) {
            // Clean up: remove child VC and views to fully detach
            [self.filterVC willMoveToParentViewController:nil];
            [self.filterVC.view removeFromSuperview];
            [self.filterVC removeFromParentViewController];
            [self removeFromSuperview];
        }];
}

#pragma mark - FilterViewControllerDelegate

- (void)filterViewController:(FilterViewController *)controller didConfirmWithSelectedOptions:(NSArray<NSString *> *)selectedOptions {
    if (self.selectionHandler) {
        self.selectionHandler(selectedOptions);
    }
    [self dismiss];
}

@end


